package org.dochandler.dao.derby;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.dochandler.config.DHConfig;
import org.dochandler.dao.MissionApprovalDAO;
import org.dochandler.service.domain.mission.MissionApproval;
import org.dochandler.service.exception.DatabaseException;

@SuppressWarnings("serial")
public class DerbyMissionApprovalDAO implements MissionApprovalDAO, Serializable {
	
	private Connection conn;
	private String derbyUrl;
	private String derbyDriver;
	
	public DerbyMissionApprovalDAO() {
		if (conn == null) {
			this.derbyUrl = DHConfig.getString("local_db_url");
			this.derbyDriver = DHConfig.getString("local_db_driver");
	
			try {
				Class.forName(derbyDriver).newInstance();
				conn = DriverManager.getConnection(derbyUrl);
			} catch (Exception e) {
				throw new DatabaseException("Could not connect to the database", e);
			}
		}
	}
	
	@Override
	public MissionApproval findById(Long entityId) {
		String sql = "SELECT * FROM APPROVED_MISSIONS ID = ?";
		
		MissionApproval missionApproval = null;
		try {
			PreparedStatement stmt = conn.prepareStatement(sql);
			
			int i = 0;
			stmt.setLong(++i, entityId);
			
			ResultSet rs = stmt.executeQuery(sql);
			
			if (rs.next()) {
				missionApproval = new MissionApproval();
			}
			
		} catch(SQLException e) {
			throw new DatabaseException("There has been a problem finding approvals", e);
		}
		return missionApproval;
	}

	@Override
	public List<MissionApproval> findAll() {
		String sql = "SELECT * FROM APPROVED_MISSIONS";
		List<MissionApproval> approvals = new ArrayList<MissionApproval>();
		
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			
			while (rs.next()) {
				MissionApproval approval = new MissionApproval();
				
				approvals.add( approval );
			}
			
		} catch(SQLException e) {
			throw new DatabaseException("Could not execute find all mission requests", e);
		}
		return approvals;
	}

	@Override
	public boolean create(MissionApproval entity) {
		return true;
	}

	@Override
	public boolean delete(Long approvalId) {
		return false;
	}

	@Override
	public boolean update(MissionApproval missionApproval) {
		return false;
	}

	@Override
	public Long approve(MissionApproval approval) {
		return null;
	}
	
}